package com.itheima.controller;

/**
 * @author ：hg
 * @date ：Created in 2021/12/19 15:49
 * @description：处理体检预约
 */

import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import com.itheima.utils.SMSUtils;
import jdk.nashorn.internal.ir.annotations.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

/**
 * 处理体检预约
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private OrderService orderService;

    //在线体检预约
    @RequestMapping("/submit")
    public Result submit(@RequestBody Map map) {
        //获取输入的手机号
        String telephone = (String) map.get("telephone");
        //获取输入的验证码
        String validateCode = (String) map.get("validateCode");
        //从Redis中获取缓存的验证码，key为手机号+RedisConstant.SENDTYPE_ORDER
        String validateInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        //进行比对
        if (null != validateInRedis && null != validateCode && validateCode.equals(validateInRedis)) {
            //如果比对成功，调用服务完成预约处理

            //通过dubbo来远程调用服务实现,一般会出现网络的一些问题，使用try..catch
            Result result = null;
            try {
                //设置预约的类型：分为微信预约、电话预约
                map.put("orderType", Order.ORDERTYPE_WEIXIN);
                result = orderService.order(map);
            } catch (Exception e) {
                e.printStackTrace();
                return result;
            }

            if (result.isFlag()) {
                //预约成功，为用户发送短信
                try {
                    SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE, telephone, (String) map.get("orderDate"));
                } catch (ClientException e) {
                    e.printStackTrace();
                }

            }
            return result;
        } else {
            //不成功，返回结果给页面,验证码输入错误
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }

    }

    //根据预约id来查询相关的预约信息
    @RequestMapping("/findById")
    public Result findById(Integer id){
        try{
            Map map = orderService.findById(id);
            return new Result(false,MessageConstant.QUERY_ORDER_SUCCESS,map);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }
    }
}





